package com.qin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.log.StaticLog;

/**
 * 拦截所有没有用户的请求
 */
@WebFilter(urlPatterns = {"/addtoshoppingcart","/shopping/*","/orders","/insertorder","/buybook","/shoppingcart"})
public class NoUserFilter implements Filter {

	@Override
	public void destroy() {
		StaticLog.debug("拦截必须带user的一些请求中");
	}

	public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain) throws IOException, ServletException {
		// 先把request转成httpServletrequest
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)rep;
		
		HttpSession session = request.getSession();
		
		// 尝试从请求域中获取user
		Object user = session.getAttribute("user");
		// 不为空就放行
		if(user != null) {
			chain.doFilter(req, rep);
		}else {
			// 重定向到首页
			response.sendRedirect(request.getContextPath());
		}
		
	}
	
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
